/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.jr2tecnologia.controller.dashboard;

import br.com.jr2tecnologia.LoggerFactory;
import br.com.jr2tecnologia.SMSMailUtil;
import br.com.jr2tecnologia.SMSUtil;
import br.com.jr2tecnologia.mail.Mailbox;
import br.com.jr2tecnologia.model.BankAccountPersistenceLocal;
import br.com.jr2tecnologia.model.LoginPersistenceLocal;
import br.com.jr2tecnologia.model.RolePersistenceLocal;
import br.com.jr2tecnologia.model.entity.BankAccount;
import br.com.jr2tecnologia.model.entity.Company;
import br.com.jr2tecnologia.model.entity.Login;
import br.com.jr2tecnologia.model.entity.Role;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.model.SelectItem;

/**
 *
 * @author ronildo
 */
@ManagedBean
@SessionScoped
public class LoginDashboardMBean implements Serializable{

    private static final Logger logger = LoggerFactory.getLogger();
    private final Login loginInSession;

    @EJB
    private LoginPersistenceLocal loginPersistence;
    @EJB
    private BankAccountPersistenceLocal bankAccountPersistence;
    @EJB
    private RolePersistenceLocal rolePersistence;

    private Login selectedLogin;
    private Login createLogin;
    private List<Login> listLogin;

    private List<Role> listRole;
    private String updateRoleSelected;
    private String persistRoleSelected;

    private List<BankAccount> listBankAccount;
    private String updateBankAccountSelected;
    private String persistBankAccountSelected;

    /** Creates a new instance of LoginDashboardMBean */
    public LoginDashboardMBean() {
        loginInSession = SMSMailUtil.getLoginInSession();
        createLogin = new Login();
        selectedLogin = new Login();
    }

    @PostConstruct
    public void initialize(){
        listLogin = loginPersistence.list(new Login(loginInSession.getCompany()));
    }

    public List<Login> getListLogin() {
        return listLogin;
    }

    public List<BankAccount> getListBankAccount() {
        return listBankAccount;
    }

    public List<Role> getListRole() {
        return listRole;
    }

    public Login getSelectedLogin() {
        return selectedLogin;
    }

    public void setSelectedLogin(Login selectedLogin) {
        this.selectedLogin = selectedLogin;
        if(selectedLogin.getRole() != null)
            updateRoleSelected = String.valueOf(selectedLogin.getRole().getPkRole());
        if(selectedLogin.getBankAccount() != null)
            updateBankAccountSelected = String.valueOf(selectedLogin.getBankAccount().getPkBankAccount());
    }

    public Login getCreateLogin() {
        return createLogin;
    }

    public void setCreateLogin(Login createLogin) {
        this.createLogin = createLogin;
    }

    public String getPersistBankAccountSelected() {
        return persistBankAccountSelected;
    }

    public void setPersistBankAccountSelected(String persistBankAccountSelected) {
        this.persistBankAccountSelected = persistBankAccountSelected;
    }

    public String getPersistRoleSelected() {
        return persistRoleSelected;
    }

    public void setPersistRoleSelected(String persistRoleSelected) {
        this.persistRoleSelected = persistRoleSelected;
    }

    public String getUpdateBankAccountSelected() {
        return updateBankAccountSelected;
    }

    public void setUpdateBankAccountSelected(String updateBankAccountSelected) {
        this.updateBankAccountSelected = updateBankAccountSelected;
    }

    public String getUpdateRoleSelected() {
        return updateRoleSelected;
    }

    public void setUpdateRoleSelected(String updateRoleSelected) {
        this.updateRoleSelected = updateRoleSelected;
    }

    public List<SelectItem> getMenuRole(){
        listRole = rolePersistence.listAll();
        List<SelectItem> menuRole = new ArrayList<SelectItem>();
        menuRole.add(new SelectItem(0, ""));
        for(Role role : listRole ){
            if(!loginInSession.getRole().getName().equals("root")){
                if(!role.getName().equals("root")){
                    menuRole.add(new SelectItem(String.valueOf(role.getPkRole()), role.getName()));
                }
            }else{
                menuRole.add(new SelectItem(String.valueOf(role.getPkRole()), role.getName()));
            }
        }

        return menuRole;
    }

    public List<SelectItem> getMenuBankAccount(){
        listBankAccount = bankAccountPersistence.listBankAccountsOfCompany(loginInSession.getCompany());

        List<SelectItem> menuBankAccount = new ArrayList<SelectItem>();
        menuBankAccount.add(new SelectItem(0, ""));
        for(BankAccount bankAccount : listBankAccount )
            menuBankAccount.add(new SelectItem(String.valueOf(bankAccount.getPkBankAccount()), bankAccount.getName()));

        return menuBankAccount;
    }

    public void searchLogin(){
        Company company = loginInSession.getCompany();
        listLogin = loginPersistence.list(new Login(company));
    }

    private boolean validateFilds(Login login){
        String msg = "Ops, não foi possivel concluir seu cadastro. Por favor volte e";
        if(login.getName().trim().equals("")){
            SMSMailUtil.putFacesMessage("",msg+" digite o nome do login. ");
            return false;
        }
        else if(login.getEmail().trim().equals("")){
            SMSMailUtil.putFacesMessage("",msg+" digite o e-mail do login. ");
            return false;
        }
        else if(login.getRole() == null){
            SMSMailUtil.putFacesMessage("",msg+" escolha um papel de acesso do login. ");
            return false;
        }
        else if(login.getBankAccount() == null){
            SMSMailUtil.putFacesMessage("",msg+" escolha uma conta para este login. ");
            return false;
        }else
            return true;
    }

    public void createLogin(){
        createLogin.setPkLogin(null);
        createLogin.setCompany(loginInSession.getCompany());
        createLogin.setActivationKey(SMSUtil.makeActivationKey());
        createLogin.setBlocked(true);
        createLogin.setDescription("user registered by login: " + loginInSession.getEmail());

        for(Role role : listRole)
            if(role.getPkRole().longValue() == Long.parseLong(persistRoleSelected))
                createLogin.setRole(role);

        for(BankAccount bankAccount : listBankAccount)
            if(bankAccount.getPkBankAccount().longValue() == Long.parseLong(persistBankAccountSelected))
                createLogin.setBankAccount(bankAccount);

        if(validateFilds(createLogin)){
            loginPersistence.persist(createLogin);

            boolean sendered = Mailbox.postNewUser(createLogin.getEmail(), createLogin.getActivationKey());
            if(sendered)
                SMSMailUtil.putFacesMessage("Sucesso","Um e-mail de confirmação e instruções de acesso foi enviado para o e-mail deste login");
        }
        searchLogin();
    }

    public void updateLogin(){
        for(Role role : listRole)
            if(role.getPkRole().longValue() == Long.parseLong(updateRoleSelected))
                selectedLogin.setRole(role);

        for(BankAccount bankAccount : listBankAccount)
            if(bankAccount.getPkBankAccount().longValue() == Long.parseLong(updateBankAccountSelected))
                selectedLogin.setBankAccount(bankAccount);

        if(validateFilds(selectedLogin)){
            loginPersistence.update(selectedLogin);
            SMSMailUtil.putFacesMessage("Sucesso","Login atualizado com sucesso");
            searchLogin();
        }
    }

    public void removeLogin(){
        loginPersistence.remove(selectedLogin);
        SMSMailUtil.putFacesMessage("Sucesso","Login removido com sucesso");
        searchLogin();
    }
}
